package wangwenjun.phase2.concurrencypattern.eventbus.framework;

import java.util.concurrent.Executor;

/**
 * @author ChangLiang
 * @date 2020/6/18
 */
public class BaseEventBus implements EventBus {

    private String eventBusName;

    private final static String DEFAULT_EVENT_BUS_NAME = "default-sync-event-bus";

    private final static String DEFAULT_TOPIC = "default-topic";

    private final SubscriberRegistry registry = new SubscriberRegistry();

    private final EventDispatcher eventDispatcher;

    /**
     * 最简单使用
     */
    public BaseEventBus() {
        this(DEFAULT_EVENT_BUS_NAME, null, EventDispatcher.SEQ_EXECUTOR_SERVICE);
    }

    public BaseEventBus(String eventBusName) {
        this(eventBusName, null, EventDispatcher.SEQ_EXECUTOR_SERVICE);
    }

    public BaseEventBus(EventExceptionHandler exceptionHandler) {
        this(DEFAULT_EVENT_BUS_NAME, exceptionHandler, EventDispatcher.SEQ_EXECUTOR_SERVICE);
    }

    /**
     * 最全参数
     * @param eventBusName
     * @param exceptionHandler
     * @param executor
     */
    public BaseEventBus(String eventBusName, EventExceptionHandler exceptionHandler, Executor executor) {
        this.eventBusName = eventBusName;
        this.eventDispatcher = EventDispatcher.newEventDispatcher(exceptionHandler, executor);
    }

    @Override
    public void register(Object subscriber) {
        this.registry.bind(subscriber);
    }

    @Override
    public void unRegister(Object subscriber) {
        this.registry.unbind(subscriber);
    }

    @Override
    public void post(Object event) {
        this.post(event,DEFAULT_TOPIC);
    }

    @Override
    public void post(Object event, String topic) {
        this.eventDispatcher.dispatchEvent(this,registry,event,topic);
    }

    @Override
    public void close() {
        this.eventDispatcher.close();
    }

    @Override
    public String getEventBusName() {
        return this.eventBusName;
    }
}
